package com.googlecode.nacl_optimizer.elf;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.googlecode.nacl_optimizer.elf.headers.ElfHeader;
import com.googlecode.nacl_optimizer.elf.headers.ProgramHeader;
import com.googlecode.nacl_optimizer.elf.headers.SectionHeader;

public class ElfFile {
    private ElfHeader header;
    private ProgramHeader programHeader;
    private byte[] data;
    private SectionHeader[] sectionHeaders;

    public ElfFile(FileInputStream fileInputStream) throws Exception {
        List<Byte> d = new ArrayList<Byte>();
        int b = 0;
        while ((b = fileInputStream.read()) != -1) {
            d.add(Byte.valueOf((byte) b));
        }
        data = new byte[d.size()];
        for (int i = 0; i < d.size(); i++) {
            data[i] = d.get(i).byteValue();
        }
        header = new ElfHeader(data);

        loadSections(header.getShoff(), header.getShnum(),
                header.getShEntSize());
    }

    private void loadSections(Integer off, Integer num, Integer size) {
        sectionHeaders = new SectionHeader[num];
        for (int i = 0; i < num; i++) {
            sectionHeaders[i] = new SectionHeader(Arrays.copyOfRange(data,
                    (off + size * i), off + size * (i + 1)), header.getEncoding());
        }
    }

    public ElfHeader getHeader() {
        return header;
    }

    public ProgramHeader getProgramHeader() {
        return programHeader;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("sections number= "+sectionHeaders.length+"\n");
        for(SectionHeader sh : sectionHeaders) {
            sb.append("Section name: "+sh.getName()+"\n");
            sb.append("Section type: "+sh.getType()+"\n");
        }
        // sb.append("\n");
        // sb.append(programHeader.toString());
        return sb.toString();
    }
}
